<template>
  <div class="customer-management">
    <!-- 主要内容区域 - 添加水平和垂直滚动容器 -->
    <div class="main-content-wrapper">
      <el-card>
        <!-- 搜索区域 -->
        <el-form :model="searchForm" class="search-form" label-width="80px">
          <el-row :gutter="20" align="middle">
            <el-col :span="6">
              <el-form-item label="手机号" inline>
                <el-input v-model="searchForm.phone" placeholder="请输入手机号" style="width: 180px;" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户姓名" inline>
                <el-input v-model="searchForm.name" placeholder="请输入客户姓名" style="width: 180px;" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="来源" inline>
                <el-select v-model="searchForm.channel" placeholder="请选择" style="width: 180px;">
                  <el-option label="全部" value="" />
                  <el-option label="推广介绍" value="1" />
                  <el-option label="线上活动" value="2" />
                  <el-option label="线下活动" value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="意向学科" inline>
                <el-select v-model="searchForm.subject" placeholder="请选择" style="width: 180px;">
                  <el-option label="全部" value="" />
                  <el-option label="AI智能应用开发(Java)" value="1" />
                  <el-option label="AI大模型开发(Python)" value="2" />
                  <el-option label="AI鸿蒙开发" value="3" />
                  <el-option label="AI大数据" value="4" />
                  <el-option label="AI嵌入式" value="5" />
                  <el-option label="AI测试" value="6" />
                  <el-option label="AI运维" value="7" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="text-align: right;">
              <el-form-item>
                <el-button type="primary" @click="handleSearch" style="margin-right: 10px;">搜索</el-button>
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        
        <!-- 操作按钮 -->
        <div class="action-buttons-left" style="margin-bottom: 20px;">
          <el-button type="primary" @click="handleAdd">新增客户</el-button>
        </div>
        
        <!-- 数据表格 -->
        <div style="overflow-x: auto;">
          <el-table 
            :data="customerList" 
            stripe 
            style="width: 100%; min-width: 1400px; font-size: 14px;"
            :header-cell-style="{ 'font-size': '14px', 'padding': '10px 12px' }"
          >
            <el-table-column label="序号" type="index" width="80" />
            <el-table-column prop="name" label="客户姓名" width="120" />
            <el-table-column prop="phone" label="手机号" width="150" />
            <el-table-column prop="channel" label="渠道来源" width="120">
              <template #default="{ row }">
                <span>{{ getChannelText(row.channel) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="degree" label="学历" width="100">
              <template #default="{ row }">
                <span>{{ getDegreeText(row.degree) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="jobStatus" label="在职状态" width="100">
              <template #default="{ row }">
                <span>{{ getJobStatusText(row.jobStatus) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="subject" label="意向学科" width="180">
              <template #default="{ row }">
                <span>{{ getSubjectText(row.subject) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="courseName" label="意向课程" width="180" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="100" align="center">
              <template #default="{ row }">
                <div style="display: flex; gap: 10px; justify-content: center;">
                  <el-button type="primary" size="small" @click="handleEdit(row)">修改</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleClose"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" maxlength="11" show-word-limit />
        </el-form-item>
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入客户姓名" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="formData.gender" placeholder="请选择性别">
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="formData.age" type="number" placeholder="请输入年龄" min="1" max="150" />
        </el-form-item>
        <el-form-item label="来源" prop="channel">
          <el-select v-model="formData.channel" placeholder="请选择来源">
            <el-option label="推广介绍" value="1" />
            <el-option label="线上活动" value="2" />
            <el-option label="线下活动" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="意向学科" prop="subject">
            <el-select v-model="formData.subject" placeholder="请选择意向学科">
              <el-option label="AI智能应用开发(Java)" value="1" />
              <el-option label="AI大模型开发(Python)" value="2" />
              <el-option label="AI鸿蒙开发" value="3" />
              <el-option label="AI大数据" value="4" />
              <el-option label="AI嵌入式" value="5" />
              <el-option label="AI测试" value="6" />
              <el-option label="AI运维" value="7" />
            </el-select>
          </el-form-item>
        <el-form-item label="意向课程" prop="courseId">
          <el-select v-model="formData.courseId" placeholder="请选择意向课程">
            <el-option label="Java核心与AI开发基础" value="1" />
            <el-option label="Python基础" value="2" />
            <el-option label="LangChain核心" value="3" />
            <el-option label="就业班课程" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="学历" prop="degree">
          <el-select v-model="formData.degree" placeholder="请选择学历">
            <el-option label="高中" value="1" />
            <el-option label="大专" value="2" />
            <el-option label="本科" value="3" />
            <el-option label="硕士" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="在职状态" prop="jobStatus">
          <el-select v-model="formData.jobStatus" placeholder="请选择在职状态">
            <el-option label="在职" value="1" />
            <el-option label="离职" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="微信" prop="wechat">
          <el-input v-model="formData.wechat" placeholder="请输入微信" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="QQ" prop="qq">
          <el-input v-model="formData.qq" placeholder="请输入QQ" maxlength="20" show-word-limit />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'CustomerManagement',
  setup() {
    // 搜索表单
    const searchForm = reactive({
      phone: '',
      name: '',
      channel: '',
      subject: ''
    })
    
    // 客户列表数据
    const customerList = ref([])
    
    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 对话框相关
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const formRef = ref(null)
    
    // 表单数据
    const formData = reactive({
      id: '',
      phone: '',
      name: '',
      gender: '1',
      age: '',
      channel: '1',
      subject: '1',
      courseId: '',
      degree: '1',
      jobStatus: '1',
      wechat: '',
      qq: '',
      businessId: null
    })
    
    // 表单验证规则
    const formRules = reactive({
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入客户姓名', trigger: 'blur' },
        { min: 1, max: 20, message: '客户姓名长度在 1 到 20 个字符', trigger: 'blur' }
      ],
      channel: [
        { required: true, message: '请选择来源', trigger: 'change' }
      ],
      subject: [
        { required: true, message: '请选择意向学科', trigger: 'change' }
      ],
      courseId: [
        { required: true, message: '请选择意向课程', trigger: 'change' }
      ]
    })
    
    // 获取渠道文本
    const getChannelText = (channel) => {
      const channelMap = {
        1: '推广介绍',
        2: '线上活动',
        3: '线下活动'
      }
      return channelMap[channel] || '未知'
    }
    
    // 获取学历文本
    const getDegreeText = (degree) => {
      const degreeMap = {
        1: '高中',
        2: '大专',
        3: '本科',
        4: '硕士'
      }
      return degreeMap[degree] || '未知'
    }
    
    // 获取在职状态文本
    const getJobStatusText = (jobStatus) => {
      const jobStatusMap = {
        1: '在职',
        2: '离职'
      }
      return jobStatusMap[jobStatus] || '未知'
    }
    
    // 获取意向学科文本
    const getSubjectText = (subject) => {
      const subjectMap = {
        1: 'AI智能应用开发(Java)',
        2: 'AI大模型开发(Python)',
        3: 'AI鸿蒙开发',
        4: 'AI大数据',
        5: 'AI嵌入式',
        6: 'AI测试',
        7: 'AI运维'
      }
      return subjectMap[subject] || '未知'
    }
    
    // 获取客户列表
    const getCustomerList = async () => {
      try {
        const params = {
          ...searchForm,
          page: pagination.currentPage,
          pageSize: pagination.pageSize
        }
        
        const response = await axios.get('/api/customers', {
          params: params
        })
        
        const result = response.data
        
        if (result && typeof result === 'object') {
          if (result.code === 1) {
            if (result.data && Array.isArray(result.data.rows)) {
              customerList.value = result.data.rows
              pagination.total = Number(result.data.total) || 0
              
              if (customerList.value.length === 0) {
                ElMessage.info('暂无数据')
              }
            } else {
              ElMessage.error('响应数据格式错误')
            }
          } else {
            ElMessage.error(result.msg || '获取客户列表失败')
          }
        } else {
          ElMessage.error('获取客户列表失败')
        }
      } catch (error) {
        console.error('获取客户列表异常:', error)
        ElMessage.error('获取客户列表失败')
      }
    }
    
    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1
      getCustomerList()
    }
    
    // 重置
    const handleReset = () => {
      searchForm.phone = ''
      searchForm.name = ''
      searchForm.channel = ''
      searchForm.subject = ''
      pagination.currentPage = 1
      getCustomerList()
    }
    
    // 新增客户
    const handleAdd = () => {
      dialogTitle.value = '新增客户'
      formData.id = ''
      formData.phone = ''
      formData.name = ''
      formData.gender = '1'
      formData.age = ''
      formData.channel = '1'
      formData.subject = '1'
      formData.courseId = ''
      formData.degree = '1'
      formData.jobStatus = '1'
      formData.wechat = ''
      formData.qq = ''
      formData.businessId = null
      
      if (formRef.value) {
        formRef.value.resetFields()
      }
      dialogVisible.value = true
    }
    
    // 编辑客户
    const handleEdit = async (row) => {
      dialogTitle.value = '修改客户'
      try {
        const response = await axios.get(`/api/customers/${row.id}`)
        const result = response.data
        
        if (result && result.code === 1 && result.data) {
          formData.id = result.data.id
          formData.phone = result.data.phone
          formData.name = result.data.name
          formData.gender = String(result.data.gender || 1)
          formData.age = result.data.age
          formData.channel = String(result.data.channel || 1)
          formData.subject = String(result.data.subject || 1)
          formData.courseId = result.data.courseId
          formData.degree = String(result.data.degree || 1)
          formData.jobStatus = String(result.data.jobStatus || 1)
          formData.wechat = result.data.wechat || ''
          formData.qq = result.data.qq || ''
          formData.businessId = result.data.businessId
        } else {
          ElMessage.error(result.msg || '获取客户信息失败')
          return
        }
      } catch (error) {
        console.error('获取客户详情异常:', error)
        ElMessage.error('获取客户信息失败')
        return
      }
      dialogVisible.value = true
    }
    
    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        
        const submitData = {
          ...formData,
          age: formData.age ? Number(formData.age) : null
        }
        
        let response
        if (submitData.id) {
          // 修改
          response = await axios.put('/api/customers', submitData)
        } else {
          // 新增
          const { id, businessId, ...addData } = submitData
          response = await axios.post('/api/customers', addData)
        }
        
        const result = response.data
        if (result && result.code === 1) {
          ElMessage.success(submitData.id ? '修改成功' : '新增成功')
          dialogVisible.value = false
          getCustomerList()
        } else {
          ElMessage.error(result.msg || '操作失败')
        }
      } catch (error) {
        if (error.name === 'Error') {
          console.error('提交表单异常:', error)
          ElMessage.error('操作失败')
        }
        // 验证失败时不显示提示
      }
    }
    
    // 关闭对话框
    const handleClose = () => {
      if (formRef.value) {
        formRef.value.resetFields()
      }
    }
    
    // 分页大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      getCustomerList()
    }
    
    // 当前页变化
    const handleCurrentChange = (current) => {
      pagination.currentPage = current
      getCustomerList()
    }
    
    // 初始化
    onMounted(() => {
      getCustomerList()
    })
    
    return {
      searchForm,
      customerList,
      pagination,
      dialogVisible,
      dialogTitle,
      formRef,
      formData,
      formRules,
      getChannelText,
      getDegreeText,
      getJobStatusText,
      getSubjectText,
      handleSearch,
      handleReset,
      handleAdd,
      handleEdit,
      handleSubmit,
      handleClose,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.customer-management {
  padding: 20px;
}

.main-content-wrapper {
  overflow-x: auto;
  overflow-y: auto;
  max-height: calc(100vh - 40px);
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.action-buttons-left {
  margin-bottom: 20px;
}

:deep(.el-table) {
  min-width: 1400px;
}
</style>
